//
//  JFTRequest.m
//  JftMergeSDK
//
//  Created by zhl on 2017/2/10.
//  Copyright © 2017年 HLZ. All rights reserved.
//

#import "JFTRequest.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import <netinet/in.h>
#import "configHeader.h"
#import "JFTDES.h"
@implementation JFTRequest
+(instancetype)requestManager{
    static JFTRequest *shareRequest =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareRequest =[self new];
    });
    return shareRequest;
}

-(BOOL)ConnectedToNetwork
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

- (void)getDataWithUrl:(NSString *)url WithParameters:(NSDictionary *)parDictionary Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    if (![self ConnectedToNetwork]) {
        failure (@"请检查网络连接！");
        return;
    }
    NSString *paraStr =nil;
    if (parDictionary) {
        NSData *mmdata =[NSJSONSerialization dataWithJSONObject:[parDictionary objectForKey:@"info"] options:NSJSONWritingPrettyPrinted error:nil];
        NSLog(@"%@",parDictionary);
        NSString *enStr=[[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
        NSString*miwen =   [JFTDES encryptWithContent:enStr type:0 key:[[JFTDES md532BitUpper:[JFTDESKEY stringByAppendingString:NONCER]] substringToIndex:8]];
        NSString *encodeURL =[JFTDES encodeToPercentEscapeString:[JFTDES replacenormalcharacter:miwen]];
        NSArray *keyArray = [parDictionary allKeys];
        NSArray *valueArray =[parDictionary allValues];
        if (keyArray.count) {
            for (int i=0; i<keyArray.count; i++) {
                if (i==0) {
                    paraStr =[NSString stringWithFormat:@"%@=%@",keyArray[i],valueArray[i]];
                }else if(i==1){
                    paraStr =[paraStr stringByAppendingString
                              :[NSString stringWithFormat:@"&%@=%@",keyArray[i],encodeURL]];
                }else{
                    paraStr =[paraStr stringByAppendingString
                              :[NSString stringWithFormat:@"&%@=%@",keyArray[i],valueArray[i]]];
                }
            }
        }

    }
    NSString *urlString =url;
    if (paraStr) {
        urlString =[NSString stringWithFormat:@"%@%@",url,paraStr];
    }
    NSURL *requesturl =[NSURL URLWithString:urlString];
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:requesturl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    NSURLSession *session =[NSURLSession sharedSession];
    NSURLSessionDataTask *task =[session dataTaskWithRequest:mutableUrlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            errorBlock(error);
            NSLog(@"---%ld---",error.code);
            return ;
        }
         NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;

        if (ponse.statusCode!=200) {
        errorBlock(error);
            return;
        }
        NSError*jsonError;
        id returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        Sucessful (returnData);

    }];

    [task resume];
}

- (void)postDataWithUrl:(NSString *)url WithParameters:(NSDictionary *)parDictionary WithNoncer:(NSString *)noncer Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    NSData *mmdata =[NSJSONSerialization dataWithJSONObject:parDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *enStr=[[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
    NSString*miwen =   [JFTDES encryptWithContent:enStr type:0 key:[[JFTDES md532BitUpper:[desKey stringByAppendingString:noncer]] substringToIndex:8]];
    NSString *encodemiWen =[JFTDES encodeToPercentEscapeString:[JFTDES replacenormalcharacter:miwen]];
    NSString *miDict = [NSString stringWithFormat:@"timeStamp=%@&msg=%@",noncer,encodemiWen];
    NSURL *requesturl =[NSURL URLWithString:url];
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:requesturl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    NSURLSession *session =[NSURLSession sharedSession];
    mutableUrlRequest.HTTPMethod = @"POST";
    mutableUrlRequest.HTTPBody = [miDict dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *task =[session dataTaskWithRequest:mutableUrlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSString *str = [NSString stringWithFormat:@"%ld",error.code];
            failure(str);
            NSLog(@"---%@---",error);
            return ;
        }
        NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;

        if (ponse.statusCode!=200) {
            NSString *str = [NSString stringWithFormat:@"%ld",error.code];
            failure(str);
            return;
        }
        NSError*jsonError;
        NSDictionary *returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];

        NSString *ddstr=[NSString stringWithFormat:@"%@",[JFTDES replacespecialcharacter:returnData[@"msg"]]];
        NSString *keyyStr=[[JFTDES md532BitUpper:[desKey stringByAppendingString:[returnData objectForKey:@"timeStamp"]]] substringToIndex:8];
        NSString*mingWen= [JFTDES encryptWithContent:ddstr type:1 key:keyyStr];
        if (!mingWen) {
            failure(@"解密失败，请重新再试");
            return;
        }
        NSError *mingError;
        id mingwenObject=[NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&mingError];
        if ([mingwenObject isKindOfClass:[NSString class]]) {

            failure(mingwenObject);
        }
        if (mingError) {
            errorBlock(mingError);
            return;
        }
        Sucessful(mingwenObject);


    }];

    [task resume];
}

- (void)loadImageWithUrl:(NSURL *)url andImage:(UIImage *)image Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    //urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSData *imageData = UIImagePNGRepresentation(image);
    NSURLSessionUploadTask *uploadTask =  [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSLog(@"upload success：%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } else {
            NSLog(@"upload error:%@",error);
        }
   }];
     [uploadTask resume];

}

- (void)downloadImageWithUrl:(NSURL *)url Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [sharedSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSString *str = [NSString stringWithFormat:@"%ld",error.code];
            failure(str);
            NSLog(@"---%@---",error);
            return ;
        }
        NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;
        if (ponse.statusCode!=200) {
            NSString *str = [NSString stringWithFormat:@"%ld",error.code];
            failure(str);
            return;
        }
        NSData *data = [NSData dataWithContentsOfFile:location.path];
        UIImage *image = [UIImage imageWithData:data];
        Sucessful(image);
    }];
    [downloadTask resume];
}
@end
